<template>
  <div class="container">
    <Breadcrumb />
    <a-card class="data-card">
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="formModel"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
          >
            <a-row :gutter="20">
              <a-col :span="5">
                <a-form-item field="caseTypeName" label="分类名称">
                  <a-input
                    v-model="formModel.caseTypeName"
                    placeholder="请输入分类名称"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <!-- <a-col :span="5">
                <a-form-item field="username" label="时间">
                  <a-range-picker @change="onChangeTime" />
                </a-form-item>
              </a-col> -->
              <a-col :span="5">
                <a-space :size="18">
                  <a-button @click="openAdd()" type="primary">
                    <template #icon>
                      <icon-plus />
                    </template>
                    新增
                  </a-button>
                  <a-button type="primary" @click="onPageChange(1)">
                    <template #icon>
                      <icon-search />
                    </template>
                    搜索
                  </a-button>
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    重置
                  </a-button>
                  <!-- <a-button type="primary" @click="openOper">
										操作日志
									</a-button> -->
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-table
        row-key="userId"
        :loading="loading"
        page-position="bottom"
        :pagination="pagination"
        :columns="columns"
        :data="renderData"
        :bordered="false"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #option="{ record }">
          <a-space :size="18">
            <a-button status="danger" @click="openDelete(record)">
              删除
            </a-button>
            <a-button @click="openEdit(record)" type="outline">
              编辑信息
            </a-button>
          </a-space>
        </template>

        <template #url="{ record }">
          <a-space :size="18">
            <div class="imgbox">
              <img :src="`${base + record.url}`" @error="handleImgError" alt=""
            /></div>
          </a-space>
        </template>
      </a-table>
    </a-card>
    <!-- 添加菜单 -->
    <a-modal
      v-model:visible="addShow"
      @cancel="handleCancel"
      :on-before-ok="handleCheck"
      :mask-closable="false"
      unmountOnClose
    >
      <template #title> 分类 </template>
      <a-form ref="addModel" :rules="rules" :model="addForm">
        <a-form-item field="caseTypeName" label="分类名称">
          <a-input
            v-model="addForm.caseTypeName"
            size="large"
            placeholder="请输入分类名称"
            :disabled="addForm.caseTypeId == 1"
          />
        </a-form-item>

        <a-form-item field="url" label="图片封面">
          <!-- :custom-request="tponProgress"  @change="tponChange"-->
          <a-upload
            :show-file-list="false"
            @progress="tponProgress"
            accept="image/*"
          >
            <template #upload-button>
              <div
                style="
                  background-color: var(--color-fill-2);
                  color: var(--color-text-1);
                  border: 1px dashed var(--color-fill-4);
                  height: 100px;
                  width: 100px;
                  border-radius: 2;
                  line-height: 100px;
                  text-align: center;
                "
              >
                <img
                  v-if="addForm.url"
                  :src="`${base + addForm.url}`"
                  alt=""
                  style="height: 100px; width: 100px"
                />
                <div v-else>上传图片</div>
              </div>
            </template>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, watch, nextTick } from 'vue';
  import { useRouter } from 'vue-router';
  import useLoading from '@/hooks/loading';
  import {
    Message,
    Modal,
    TableColumnData,
    ValidatedError,
  } from '@arco-design/web-vue';
  import {
    typeList,
    typeRemove,
    addType,
    typeUpdate,
    addimg,
  } from '@/api/case';
  import { Pagination } from '@/types/global';
  const { loading, setLoading } = useLoading(true);

  // 钩子
  const generateFormModel = () => {
    return {
      caseTypeName: '',
    };
  };

  const base = ref((window as any).config.VUE_APP_IMG_API);
  const formModel = ref(generateFormModel());
  //   添加
  const renderData = ref([]);
  //   定义查询接口
  const fetchData = async () => {
    setLoading(true);
    try {
      const data = {
        pageNum: pagination.current,
        ...pagination,
        ...formModel.value,
      };
      typeList(data).then((res) => {
        renderData.value = res.data.list;
        pagination.total = res.data.total;
        pagination.current = res.data.pageNum;
      });
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  //   定义相关参数
  const basePagination: Pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
  };
  const pagination = reactive({
    ...basePagination,
    'hide-on-single-page': true,
    'show-total': true,
    'show-jumper': true,
    'show-page-size': true,
  });
  //   查找 充实

  const onPageChange = (current: number) => {
    pagination.current = current;
    fetchData();
  };
  const onPageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    fetchData();
  };
  //   重置
  const reset = () => {
    formModel.value = generateFormModel();
    fetchData();
  };

  fetchData();

  const columns = computed<TableColumnData[]>(() => [
    {
      title: 'ID',
      dataIndex: 'caseTypeId',
    },
    {
      title: '封面',
      dataIndex: 'url',
      slotName: 'url',
    },
    {
      title: '分类名称',
      dataIndex: 'caseTypeName',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '创建人',
      dataIndex: 'createUserName',
    },

    {
      title: '功能',
      slotName: 'option',
    },
  ]);

  const addShow = ref(false);
  //   新增
  const openAdd = () => {
    addShow.value = true;
  };

  // 删除
  const openDelete = (item: any) => {
    Modal.confirm({
      title: '提示',
      content: '确认删除吗？',
      onOk() {
        typeRemove({
          caseTypeId: item.caseTypeId,
        }).then((res: any) => {
          if (res.code == '200') {
            Message.success({
              //   content: res.message,
              content: '删除成功',
            });
            fetchData();
          }
        });
      },
    });
  };

  const rules = {
    caseTypeName: [
      {
        required: true,
        message: '请输入分类名称',
      },
      {
        maxLength: 20,
        message: '最长20位',
      },
    ],
    url: [
      {
        required: true,
        message: '请上传病例封面',
      },
    ],
  };
  const generateDataModel = () => {
    return {
      caseTypeName: '',
      url: '',
      caseTypeId: 0,
    };
  };
  const addForm = ref(generateDataModel());

  const handleCancel = () => {
    addForm.value = generateDataModel();
  };
  const addModel = ref();
  const handleCheck = (done: (arg0: boolean) => void) => {
    if (loading.value) {
      done(false);
      return;
    }
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1500);
    addModel.value.validate(
      async (errors: undefined | Record<string, ValidatedError>) => {
        if (!errors) {
          if (addForm.value.caseTypeId) {
            typeUpdate({
              caseTypeName: addForm.value.caseTypeName,
              url: addForm.value.url,
              caseTypeId: addForm.value.caseTypeId,
            }).then((res: any) => {
              if (res.code == '200') {
                Message.success({
                  //   content: res.message,
                  content: '编辑成功',
                });
                addForm.value = generateDataModel();
                done(true);
                fetchData();
              } else {
                done(false);
              }
            });
          } else {
            addType({
              caseTypeName: addForm.value.caseTypeName,
              url: addForm.value.url,
            }).then((res: any) => {
              if (res.code == '200') {
                Message.success({
                  //   content: res.message,
                  content: '新增成功',
                });
                addForm.value = generateDataModel();
                done(true);
                fetchData();
              } else {
                done(false);
              }
            });
          }
        } else {
          done(false);
        }
      }
    );
  };

  //   处理图片进度
  const tponProgress = (currentFile: any) => {
    let formData = new FormData();
    formData.append('file', currentFile.file);
    addimg(formData).then((res: any) => {
      if (res.code == 200) {
        addForm.value.url = res.data;
        addModel.value.validateField('url');
        console.log('上传成功', res.data);
      }
    });
  };
  //   图片加载失败
  const handleImgError = (event: any) => {
    console.log(event, '出发');

    event.target.src = '/public/error.png'; // 设置占位图片
  };

  const openEdit = (item: any) => {
    addForm.value = Object.assign({}, item);
    addShow.value = true;
  };
</script>

<style scoped>
  .imgbox {
    width: 50px;
    height: 50px;
    overflow: hidden;
  }
  .imgbox img {
    width: 50px;
    height: 50px;
  }
</style>
